import { FilterPattern, createFilter } from '@rollup/pluginutils'
import fs, { promises as fsPromises, readFileSync, statSync } from 'node:fs'
import { homedir } from 'node:os'
import { parse } from 'node:path'
import { isRoot } from './root'

const _homedir = () => {
    const env = process.env
    const home = env.HOME
    const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME
    if (process.platform === 'win32') {
        return env.USERPROFILE || (env.HOMEDRIVE || '') + env.HOMEPATH || home || null
    }

    if (process.platform === 'darwin') {
        return home || (user ? '/Users/' + user : null)
    }

    if (process.platform === 'linux') {
        return home || (isRoot() ? '/root' : user ? '/home/' + user : null)
    }

    return home || null
}

export const userHome = typeof homedir === 'function' ? homedir : _homedir

export const pathExists = async (path) => {
    try {
        await fsPromises.access(path)
        return true
    } catch {
        return false
    }
}

export const pathExistsSync = (path) => {
    try {
        fs.accessSync(path)
        return true
    } catch {
        return false
    }
}
export type FilePattern = FilterPattern

export const existPath = (id: string, include?: FilterPattern, exclude?: FilterPattern) => {
    return createFilter(include, exclude)(id)
}

export const isDir = function (path: string) {
    const stats = statSync(path)
    if (stats.isDirectory()) {
        return true
    }
    return false
}

export const getFileName = (path: string) => {
    return parse(path).name
}

export const getJson = (path: string) => {
    try {
        return JSON.parse(readFileSync(path).toString())
    } catch {
        return {}
    }
}
